const MESSAGE_KEY = 'custom-message';

let currentPageEventHandler;

class Message {
  constructor(msg) {
    this.type = 'custom-message';
    this.msg = msg;
  }
}

export class CommandMessage extends Message {
  // eslint-disable-next-line no-useless-constructor
  constructor(name, value) {
    super({
      name,
      value,
    });
  }
}

export function detectIsCustomMessage(data) {
  return data && data.type === MESSAGE_KEY;
}

export const READY_FLAG = '__iframe:ok__'

function handleEvent(cb) {
  return function (e) {
    let data = e.data
    let isCustom = detectIsCustomMessage(data)
    if (isCustom) {
      let {name, value} = data.msg
      if (cb) {
        cb(name, value)
      }
      // if (name === '__iframe:ok__') {
      //   iframeCached = value
      // }
      // if (name === 'iframe:beforeUpload') {
      //   console.log('iframe:beforeUpload')
      //   ZY_EXT.store.removeItem(global_pageStoreName)
      // }
    }
  }
}

/**
 * 添加消息监听
 * @param cb
 */
export function onMessage(cb) {
  currentPageEventHandler = handleEvent(cb)
  window.addEventListener('message', currentPageEventHandler)
}

/**
 * 取消message监听
 */
export function offMessage() {
  window.removeEventListener('message', currentPageEventHandler)
}

export function sendMessage(type, data = {}) {
  window.parent.postMessage(
    new CommandMessage(type, data),
    '*')
}
